package com.jing.ads.log;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import android.os.Environment;
import android.util.Log;

import com.jing.ads.downloader.Constants;

public class Logger {

	public static final boolean isDebug = false;
	
	private static Logger logger = null;
	private SimpleDateFormat formatter = null;
	private File logFile;
	private boolean isStop = false;

	FileOutputStream fos;
	OutputStreamWriter osw;
	BufferedWriter bw;

	private BlockingQueue<String> queue;

	private Logger() {
		init();
	}

	public void onDestroy() {
		try {
			if (fos != null) {
				fos.close();
			}
			if (osw != null) {
				osw.close();
			}
			if (bw != null) {
				bw.close();
			}
			isStop = true;
			queue.clear();
			logger = null;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static Logger getInstance() {
		if (logger == null) {
			logger = new Logger();
		}
		return logger;
	}

	private void init() {
		formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		queue = new LinkedBlockingQueue<String>(1000);
		String root = Environment.getExternalStorageDirectory().getPath();
		File base = new File(root + Constants.DEFAULT_DL_SUBDIR);
		if (!base.exists()) {
			base.mkdirs();
		}
		if (base.isDirectory()) {
			logFile = new File(base, Constants.DEFAULT_LOG_SUBDIR);
			if (!logFile.exists()) {
				try {
					logFile.createNewFile();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	public void log(String tag, String log) {
		Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
		String date = formatter.format(curDate);
		String msg = date + "  " + tag + "  " + log + System.getProperty("line.separator");
		Log.i("ADS_LOG", msg);
//		queue.add(msg);
		new LogThread(msg).start();
	}

	private class LogThread extends Thread {

		private String msg = "";
		
		public LogThread(String msg) {
			this.msg = msg;
		}
		
		@Override
		public void run() {
			try {
				fos = new FileOutputStream(logFile, true);
				osw = new OutputStreamWriter(fos);
				bw = new BufferedWriter(osw);
				bw.write(msg);
				bw.flush();
				if (fos != null) {
					fos.close();
				}
				if (osw != null) {
					osw.close();
				}
				if (bw != null) {
					bw.close();
				}
				Thread.sleep(200);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

}
